package com.wen.edu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wen.commonutils.GuLiUtils;
import com.wen.commonutils.ResultEntity;
import com.wen.commonutils.ordervo.OrderUcenterMember;
import com.wen.edu.api.UcenterApi;
import com.wen.edu.entity.Comment;
import com.wen.edu.service.CommentService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author wen
 * @since 2021-06-17
 */
@RestController
@RequestMapping("/edu/service/comment")
public class CommentController {
    @Resource
    private CommentService commentService;
    @Resource
    private UcenterApi ucenterApi;

    /**
     * 条件分页查询当前课程评论信息
     *
     * @param page 当前页
     * @param size 每页显示数量
     * @return result of operation
     */
    @GetMapping("pageComment/{page}/{size}")
    public ResultEntity pageComment(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @RequestParam("courseId") String courseId) {
        Page<Comment> pageComment = new Page<>(page, size);
//        根据当前课程id查询当前课程所属的评论
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        commentService.page(pageComment, wrapper);

        Map<String, Object> map = new HashMap<>();

        List<Comment> records = pageComment.getRecords();
        map.put("records", records);
        map.put("current", pageComment.getCurrent());
        map.put("pages", pageComment.getPages());
        map.put("size", pageComment.getSize());
        map.put("total", pageComment.getTotal());
        map.put("hasNext", pageComment.hasNext());
        map.put("hasPrevious", pageComment.hasPrevious());
        return ResultEntity.ok().data(map);
    }


    /**
     * 添加评论
     *
     * @param comment 评论内容
     * @param request 请求对象(包含token)
     * @return result of operation
     */
    @PostMapping("addComment")
    public ResultEntity addComment(@RequestBody Comment comment, HttpServletRequest request) {
//        先判断当前状态是否为登录
        String memberId = GuLiUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isEmpty(memberId)) return ResultEntity.error().message("请登录后再评论");
//        根据会员id查询会员信息
        OrderUcenterMember orderUcenterMember = ucenterApi.getMemberInfoById(memberId);
//        设置会员id-昵称-头像
        comment.setMemberId(memberId);
        comment.setNickname(orderUcenterMember.getNickname());
        comment.setAvatar(orderUcenterMember.getAvatar());
        boolean save = commentService.save(comment);
        if (save)
            return ResultEntity.ok().message("评论添加成功");
        return ResultEntity.error().message("评论添加失败");
    }
}

